﻿using System;
using System.Collections.Generic;
using System.Web;

namespace WxPayAPI
{
    public class NativePay
    {
        /**
        * 生成扫描支付模式一URL
        * @param productId 商品ID
        * @return 模式一URL
        */
        public string GetPrePayUrl(string productId)
        {
            Log.Info(this.GetType().ToString(), "Native pay mode 1 url is producing...");

            WxPayData data = new WxPayData();
            data.SetValue("appid", WxPayConfig.APPID);//公众帐号id
            data.SetValue("mch_id", WxPayConfig.MCHID);//商户号
            data.SetValue("time_stamp", WxPayApi.GenerateTimeStamp());//时间戳
            data.SetValue("nonce_str", WxPayApi.GenerateNonceStr());//随机字符串
            data.SetValue("product_id", productId);//商品ID
            data.SetValue("sign", data.MakeSign());//签名
            string str = ToUrlParams(data.GetValues());//转换为URL串
            string url = "weixin://wxpay/bizpayurl?" + str;

            Log.Info(this.GetType().ToString(), "Get native pay mode 1 url : " + url);
            return url;
        }


        public string GetPrePayUrl(string productId,string appid,string merchantid,string key,string totalamount)
        {

            var price =Convert.ToInt32(Convert.ToDecimal(totalamount) * 100);

            WxPayData data = new WxPayData();
            data.SetValue("appid", appid);//公众帐号id
            data.SetValue("mch_id", merchantid);//商户号
            data.SetValue("total_fee", price);//总金额
            data.SetValue("time_stamp", WxPayApi.GenerateTimeStamp());//时间戳
            data.SetValue("nonce_str", WxPayApi.GenerateNonceStr());//随机字符串
            data.SetValue("product_id", productId);//商品ID
            data.SetValue("sign", data.MakeSign(key));//签名
            string str = ToUrlParams(data.GetValues());//转换为URL串
            string url = "weixin://wxpay/bizpayurl?" + str;

            Log.Info(this.GetType().ToString(), "Get native pay mode 1 url : " + url);
            return url;
        }

        /// <summary>
        /// 获得统一下单接口返回的二维码链接
        /// </summary>
        /// <param name="OrderId"></param>
        /// <param name="productId"></param>
        /// <param name="appid"></param>
        /// <param name="merchantid"></param>
        /// <param name="key"></param>
        /// <param name="totalamount"></param>
        /// <param name="sub_mch_id"></param>
        /// <param name="productname"></param>
        /// <returns></returns>
        public string native1(string OrderId,string productId,string appid, string merchantid, string key, string totalamount,string sub_mch_id,string productname)
        {

            //Log.Info(this.GetType().ToString(), "Native pay mode 2 url is producing...");
            var price = Convert.ToInt32(Convert.ToDecimal(totalamount) * 100);

            WxPayData data = new WxPayData();
            data.SetValue("body", productname);//商品描述
            data.SetValue("out_trade_no", OrderId);//随机字符串WxPayApi.GenerateOutTradeNo()
            data.SetValue("total_fee", price);//总金额
            data.SetValue("time_start", DateTime.UtcNow.AddHours(8).ToString("yyyyMMddHHmmss"));//交易起始时间
            data.SetValue("time_expire", DateTime.UtcNow.AddHours(8).AddMinutes(30).ToString("yyyyMMddHHmmss"));//交易结束时间
           
            data.SetValue("trade_type", "NATIVE");//交易类型NATIVE
            data.SetValue("product_id", productId);//商品ID
            data.SetValue("sub_mch_id", sub_mch_id);//
            WxPayData result = WxPayApi.UnifiedOrder(data,appid,merchantid,key);//调用统一下单接口

            var r = result.GetValue("code_url");

            if (r == null)
            {
                return null;

            }
            string url = r.ToString();//获得统一下单接口返回的二维码链接
            return url;

        }
        /// <summary>
        /// 获得统一下单接口返回的二维码链接
        /// </summary>
        /// <param name="OrderId"></param>
        /// <param name="productId"></param>
        /// <param name="appid"></param>
        /// <param name="merchantid"></param>
        /// <param name="key"></param>
        /// <param name="totalamount"></param>
        /// <param name="sub_mch_id"></param>
        /// <param name="productname"></param>
        /// <param name="notify_url"></param>
        /// <returns></returns>
        public string native1(string OrderId, string productId, string appid, string merchantid, string key, string totalamount, string sub_mch_id, string productname,string notify_url)
        {

            //Log.Info(this.GetType().ToString(), "Native pay mode 2 url is producing...");
            var price = Convert.ToInt32(Convert.ToDecimal(totalamount) * 100);

            WxPayData data = new WxPayData();
            data.SetValue("body", productname);//商品描述
            data.SetValue("out_trade_no", OrderId);//随机字符串WxPayApi.GenerateOutTradeNo()
            data.SetValue("total_fee", price);//总金额
            data.SetValue("time_start", DateTime.UtcNow.AddHours(8).ToString("yyyyMMddHHmmss"));//交易起始时间
            data.SetValue("time_expire", DateTime.UtcNow.AddHours(8).AddMinutes(30).ToString("yyyyMMddHHmmss"));//交易结束时间

            data.SetValue("trade_type", "NATIVE");//交易类型NATIVE
            data.SetValue("product_id", productId);//商品ID
            data.SetValue("sub_mch_id", sub_mch_id);//
            WxPayData result = WxPayApi.UnifiedOrder(data, appid, merchantid, key, notify_url);//调用统一下单接口

            var r = result.GetValue("code_url");

            if (r == null)
            {
                return null;

            }
            string url = r.ToString();//获得统一下单接口返回的二维码链接
            return url;

        }
        public string native_prepayid(string OrderId, string productId, string appid, string merchantid, string key, string totalamount, string sub_mch_id, string productname, string notify_url)
        {

            //Log.Info(this.GetType().ToString(), "Native pay mode 2 url is producing...");
            var price = Convert.ToInt32(Convert.ToDecimal(totalamount) * 100);

            WxPayData data = new WxPayData();
            data.SetValue("body", productname);//商品描述
            data.SetValue("out_trade_no", OrderId);//随机字符串WxPayApi.GenerateOutTradeNo()
            data.SetValue("total_fee", price);//总金额
            data.SetValue("time_start", DateTime.UtcNow.AddHours(8).ToString("yyyyMMddHHmmss"));//交易起始时间
            data.SetValue("time_expire", DateTime.UtcNow.AddHours(8).AddMinutes(30).ToString("yyyyMMddHHmmss"));//交易结束时间

            data.SetValue("trade_type", "APP");//交易类型NATIVE
            data.SetValue("product_id", productId);//商品ID
            data.SetValue("sub_mch_id", sub_mch_id);//
            WxPayData result = WxPayApi.UnifiedOrder(data, appid, merchantid, key, notify_url);//调用统一下单接口

            var r = result.GetValue("prepay_id");

            if (r == null)
            {
                return null;

            }
            string url = r.ToString();//获得统一下单prepay_id
            return url;

        }
        public string native_prepayid(string OrderId, string productId, string totalamount, string productname, string notify_url)
        {

            //Log.Info(this.GetType().ToString(), "Native pay mode 2 url is producing...");
            var price = Convert.ToInt32(Convert.ToDecimal(totalamount) * 100);

            WxPayData data = new WxPayData();
            data.SetValue("body", productname);//商品描述
            data.SetValue("out_trade_no", OrderId);//随机字符串WxPayApi.GenerateOutTradeNo()
            data.SetValue("total_fee", price);//总金额
            data.SetValue("time_start", DateTime.UtcNow.AddHours(8).ToString("yyyyMMddHHmmss"));//交易起始时间
            data.SetValue("time_expire", DateTime.UtcNow.AddHours(8).AddMinutes(30).ToString("yyyyMMddHHmmss"));//交易结束时间

            data.SetValue("trade_type", "APP");//交易类型App
            data.SetValue("product_id", productId);//商品ID
           
            WxPayData result = WxPayApi.UnifiedOrder(data, notify_url);//调用统一下单接口

            var r = result.GetValue("prepay_id");

            if (r == null)
            {
                return null;

            }
            string url = r.ToString();//获得统一下单prepay_id
            return url;

        }



        public WxPayData native(string OrderId, string productId, string totalamount, string productname, string notify_url,string sub_appid,string sub_mch_id,string sub_openid)
        {


            var price = Convert.ToInt32(Convert.ToDecimal(totalamount) * 100);

            WxPayData data = new WxPayData();
            data.SetValue("body", productname);//商品描述
            data.SetValue("out_trade_no", OrderId);//随机字符串WxPayApi.GenerateOutTradeNo()
            data.SetValue("total_fee", price);//总金额
            data.SetValue("time_start", DateTime.UtcNow.AddHours(8).ToString("yyyyMMddHHmmss"));//交易起始时间
            data.SetValue("time_expire", DateTime.UtcNow.AddHours(8).AddMinutes(30).ToString("yyyyMMddHHmmss"));//交易结束时间

            data.SetValue("trade_type", "JSAPI");//交易类型
            data.SetValue("product_id", productId);//商品ID

            data.SetValue("sub_appid", sub_appid);

            data.SetValue("sub_mch_id", sub_mch_id);

            data.SetValue("sub_openid", sub_openid);

            WxPayData result = WxPayApi.UnifiedOrder(data, notify_url);//调用统一下单接口

            return result;

          




        }
        
        
        /**
        * 生成直接支付url，支付url有效期为2小时,模式二
        * @param productId 商品ID
        * @return 模式二URL
        */
        public WxPayData GetPayUrl(string productId)
        {
            Log.Info(this.GetType().ToString(), "Native pay mode 2 url is producing...");

            WxPayData data = new WxPayData();
            data.SetValue("body", "test");//商品描述
            data.SetValue("attach", "test");//附加数据
            data.SetValue("out_trade_no", WxPayApi.GenerateOutTradeNo());//随机字符串
            data.SetValue("total_fee", 1);//总金额
            data.SetValue("time_start", DateTime.UtcNow.AddHours(8).ToString("yyyyMMddHHmmss"));//交易起始时间
            data.SetValue("time_expire", DateTime.UtcNow.AddHours(8).AddMinutes(10).ToString("yyyyMMddHHmmss"));//交易结束时间
            data.SetValue("goods_tag", "jjj");//商品标记
            data.SetValue("trade_type", "JSAPI");//交易类型NATIVE
            data.SetValue("product_id", productId);//商品ID
            data.SetValue("sub_mch_id", WxPayConfig.sub_mch_id);//
            data.SetValue("openid", "oWo4Z1YLT5FGD39T3ot-1J3SLBLE");//oBNTojijR202SQAsAR66pKU0irD0//oBNTojjRO4QISqdxOudQBa_YYGaI
            WxPayData result = WxPayApi.UnifiedOrder(data);//调用统一下单接口
           //  string url = result.GetValue("code_url").ToString();//获得统一下单接口返回的二维码链接

            //Log.Info(this.GetType().ToString(), "Get native pay mode 2 url : " + url);
            // return url;
            //return JsonConvert.
            return result;
        }
        public WxPayData GetPayUrl(string subject,string orderid,string productId,string open_id,string subid,int amount)
        {
            Log.Info(this.GetType().ToString(), "Native pay mode 2 url is producing...");

            WxPayData data = new WxPayData();
            data.SetValue("body", subject);//商品描述
            data.SetValue("attach", "微信支付");//附加数据
            data.SetValue("out_trade_no", orderid);//随机字符串
            data.SetValue("total_fee", amount);//总金额
            data.SetValue("time_start", DateTime.UtcNow.AddHours(8).ToString("yyyyMMddHHmmss"));//交易起始时间
            data.SetValue("time_expire", DateTime.UtcNow.AddHours(8).AddMinutes(10).ToString("yyyyMMddHHmmss"));//交易结束时间
            data.SetValue("goods_tag", productId);//商品标记
            data.SetValue("trade_type", "JSAPI");//交易类型NATIVE
            data.SetValue("product_id", productId);//商品ID
            data.SetValue("sub_mch_id", subid);//
            data.SetValue("openid", open_id);//oBNTojijR202SQAsAR66pKU0irD0//oBNTojjRO4QISqdxOudQBa_YYGaI
            WxPayData result = WxPayApi.UnifiedOrder(data);//调用统一下单接口
                                                           //  string url = result.GetValue("code_url").ToString();//获得统一下单接口返回的二维码链接

            //Log.Info(this.GetType().ToString(), "Get native pay mode 2 url : " + url);
            // return url;
            //return JsonConvert.
            return result;
        }
        
        /**
        * 参数数组转换为url格式
        * @param map 参数名与参数值的映射表
        * @return URL字符串
        */
        private string ToUrlParams(SortedDictionary<string, object> map)
        {
            string buff = "";
            foreach (KeyValuePair<string, object> pair in map)
            {
                buff += pair.Key + "=" + pair.Value + "&";
            }
            buff = buff.Trim('&');
            return buff;
        }
        /// <summary>
        /// 提交被扫支付API
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="merchantid"></param>
        /// <param name="body"></param>
        /// <param name="out_trade_no"></param>
        /// <param name="total_fee"></param>
        /// <param name="auth_code"></param>
        /// <returns></returns>
        public string Micropay(string appid,string merchantid,string sub_merchantid,string body,string out_trade_no,int total_fee,string auth_code, string key)
        {
            var data = new WxPayData();
            data.SetValue("appid",appid);
            data.SetValue("mch_id",merchantid);
            data.SetValue("total_fee", total_fee);
            data.SetValue("body", body);
            data.SetValue("out_trade_no", out_trade_no);
            data.SetValue("auth_code", auth_code);
            //data.SetValue("notify_url", "http://qr.cens.cn/CraftsManPay/WxOrderResult");
            if (!string.IsNullOrEmpty(sub_merchantid))
            {
                data.SetValue("sub_mch_id", sub_merchantid);//

            }

            var result =WxPayApi.Micropay(data,key);//调用统一下单接口

            return result;

        }

        public WxPayData CloseOrder(string appid,string merchantid,string sub_merchantid,string out_trade_no,string key)
        {
            var data = new WxPayData();
            data.SetValue("appid", appid);
            data.SetValue("mch_id", merchantid);
            data.SetValue("sub_mch_id", sub_merchantid);
            data.SetValue("out_trade_no", out_trade_no);

            var result = WxPayApi.CloseOrder(data,key);

            return result;

            

        }
        public WxPayData Reverse(string appid, string merchantid, string sub_merchantid, string out_trade_no, string key)
        {
            var data = new WxPayData();
            data.SetValue("appid", appid);
            data.SetValue("mch_id", merchantid);
            data.SetValue("sub_mch_id", sub_merchantid);
            data.SetValue("out_trade_no", out_trade_no);

            var result = WxPayApi.Reverse(data, key);

            return result;



        }
        public WxPayData Query(string appid, string merchantid, string sub_merchantid, string out_trade_no, string key)
        {
            var data = new WxPayData();
            data.SetValue("appid", appid);
            data.SetValue("mch_id", merchantid);
            data.SetValue("sub_mch_id", sub_merchantid);
            data.SetValue("out_trade_no", out_trade_no);

            var result = WxPayApi.OrderQuery(data, key);

            return result;



        }
    }
}